<template>
  <div class="kpl-stock-list">
    <h2>KPL股票龙虎榜数据</h2>
    <!-- 添加日期选择器 -->
    <div class="date-selector">
      <label for="stock-date">选择日期：</label>
      <input 
        type="date" 
        id="stock-date" 
        v-model="selectedDate" 
        :max="today"
      />
      <button @click="fetchKplStocks">查询</button>
    </div>
    <div v-if="loading">加载中...</div>
    <div v-else-if="error">{{ error }}</div>
    <div v-else>
      <!-- 添加 .table-container 类 -->
      <div class="table-container" v-if="stocks.length > 0">
        <table>
          <thead>
            <tr>
              <th>股票代码</th>
              <th>股票名称</th>
              <th>最新价</th>
              <th>涨跌幅</th>
              <th>成交额</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(stock, index) in stocks" :key="index">
              <td>{{ stock[0] }}</td>
              <td>{{ stock[1] }}</td>
              <td>{{ stock[2] }}</td>
              <td>{{ stock[3] }}</td>
              <td>{{ stock[4] }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div v-else>
        暂无数据
      </div>
      
      <!-- 分页控件 -->
      <div class="pagination" v-if="stocks.length > 0">
        <button @click="changePage(currentPage - 1)" :disabled="currentPage <= 1">上一页</button>
        <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
        <button @click="changePage(currentPage + 1)" :disabled="currentPage >= totalPages">下一页</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 定义股票数据类型
interface StockData {
  [key: number]: string | number
}

const stocks = ref<StockData[]>([])
const loading = ref<boolean>(false)
const error = ref<string | null>(null)
const selectedDate = ref<string>('')
const today = ref<string>('')
const currentPage = ref<number>(1)
const totalPages = ref<number>(150) // 假设有10页数据，实际应用中应该从API获取

// 设置今天的日期作为最大可选日期
onMounted(() => {
  const now = new Date()
  today.value = now.toISOString().split('T')[0]
  selectedDate.value = today.value
  // 组件挂载时获取今天的数据
  fetchKplStocks()
})

// 获取KPL股票数据
const fetchKplStocks = async () => {
  loading.value = true
  error.value = null
  
  try {
    // 构造带日期参数的API请求URL
    let url = `/api/api/v1/kpl-stocks/fetch-from-api?page=${currentPage.value}&page_size=50`
    if (selectedDate.value) {
      url += `&date=${selectedDate.value}`
    }
    
    // 使用相对路径调用后端API
    const response = await fetch(url)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data = await response.json()
    stocks.value = data
  } catch (err) {
    error.value = '获取数据失败: ' + (err as Error).message
    console.error('获取KPL股票数据失败:', err)
  } finally {
    loading.value = false
  }
}

// 切换页面
const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    fetchKplStocks()
  }
}
</script>

<style scoped>
.kpl-stock-list {
  padding: 20px;
}

.date-selector {
  margin-bottom: 20px;
}

.date-selector label {
  margin-right: 10px;
  font-weight: bold;
}

.date-selector input {
  margin-right: 10px;
  padding: 5px;
}

.date-selector button {
  padding: 5px 15px;
  background-color: #42b883;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.date-selector button:hover {
  background-color: #359c6d;
}

/* 新增 .table-container 样式 */
.table-container {
  max-height: 500px; /* 设置最大高度 */
  overflow-y: auto; /* 启用垂直滚动 */
}

/* 确保表格宽度适应容器 */
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
  font-weight: bold;
}

tr:nth-child(even) {
  background-color: #f9f9f9;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.pagination button {
  padding: 5px 10px;
  margin: 0 5px;
  background-color: #42b883;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.pagination span {
  margin: 0 10px;
}
</style>